﻿using Blm.RabbitMQ.MessageQueue;
using Blm.RabbitMQ.Models;
using Blm.Utils.Extensions;
using Meta.RabbitMQ.Generic;
using Microsoft.Extensions.Logging;
using RabbitMQ.Client;
using System;
using System.Threading.Tasks;
using VisionCloud.Domain.DtoModel.RabbitMq;
using VisionCloud.Domain.Repository.Interface.Ms;
using VisionCloud.Service.Fms;

namespace VisionCloud.Web.Service.MQListener
{
    public class ProjectPublishBackgroundService : BlmRabbitMQStorageSubscriberBase<ProjectPublishDto>
    {
        private readonly ILogger<ProjectPublishBackgroundService> logger;
        private readonly IMsProjectRepository msProjectRepository;
        private readonly ProjectDCService projectDCService;

        public ProjectPublishBackgroundService(IServiceProvider serviceProvider,
            ILogger<ProjectPublishBackgroundService> logger,
            IMsProjectRepository msProjectRepository,
            ProjectDCService projectDCService) : base(serviceProvider)
        {
            this.logger = logger;
            this.msProjectRepository = msProjectRepository;
            this.projectDCService = projectDCService;
        }

        public override StorageWayEm StorageWay => StorageWayEm.OnlyStorage;

        public override ClientOption ClientOption => new ClientOption("visioncloud_project_publish_exchange", "visioncloud_routingkey", ExchangeType.Topic, "visioncloud_project_publish_queue", RabbitMQConnectPoolName.CloudServerHost);

        public override async Task InvokeAsync(ProjectPublishDto model)
        {
            try
            {
                if (model == null)
                    throw new ArgumentNullException("反序列化ProjectPublishDto失败");

                var project = await msProjectRepository.GetByIdAsync(model.ProjectId);
                if (project == null) return;
                await projectDCService.AddBuilding(project);
            }
            catch (Exception ex)
            {
                logger.LogError($"ProjectPublishBackgroundService报错：{ex.Message}，{ex.StackTrace}，队列消息：{model?.ToJsonStr()}", ex);
            }
        }
    }
}
